/*
* @Author: jh
* @Date: 2018/4/10
* @description: 系统 权限添加
*/
<template>
  <div>
     <el-dialog title="权限编辑" :visible=true center width="50%" :before-close="isShowAuthFun" :close-on-click-modal=false :append-to-body=true>
         <div class="ca_permission">
        <el-form
            :model="ruleForm"
            ref="ruleForm"
            class="demo-ruleForm">
            <el-tree
                :expand-on-click-node="false"
                class="ca_per_tree"
                :data="tableData"
                show-checkbox
                default-expand-all
                node-key="id"
                ref="tree"
                highlight-current
                :props="defaultProps"
                :filter-node-method="filterNode">
            </el-tree>
            <el-form-item align="center" class="sumit" >
                <el-button type="primary" @click="getRoleAuthList()" class=" user-add-button" round>提交</el-button>
                <el-button type="primary" @click="isShowAuthFun()" round>取消</el-button>
            </el-form-item>
        </el-form>
    </div>
    </el-dialog>
  </div>
</template>
<script lang="ts">
import Vue from 'vue';
import { Component, Watch, Prop } from 'vue-property-decorator';
import RoleService from '../../../service/system-config/role';
import { SysGrantMenuTree, MenuDto } from '../../../api/Interface';
interface SysGrantMenuTreeInfo extends SysGrantMenuTree {
    children: Array<SysGrantMenuTreeInfo>;         //子节点
    disabled?: boolean; // 是否可操作性
    checkedAll: boolean; // 是否全选
    checked: boolean; // 子项是否选择
    isIndeterminate: boolean; // 不定选
    checkedList: string[]; // 子项已选的 name
    textId: number; // 显示的权重（字段的先后顺序）
}
@Component({
  components: { }
})
export default class CompanyList extends Vue {
  // 初始化数据 相当于data
  public msg: number = 123;
  public tableData: SysGrantMenuTreeInfo[] = []; // 后台数据
  public ruleForm: object = {}; // 表单
  public totalCount: number = 0; // 总数
  public currentPage: number = 1; // 当前页
  public dialogFormVisible: boolean = true; 
  public defaultProps: object = { children: 'children', label: 'text', id: 'id', pid: 'pid' }; // 默认
  public menuIds: string[] = []; //存储id
  // refs
  public $refs: {
    tree: any
   };
  @Prop()
  public isShowAuthFun: () => void;
  @Prop({default: '-1'})
  public id: string;
  // watch
  @Watch('msg')
  public onChildChanged(val: string, oldVal: string) {
    return val + '***';
  }

  // 声明周期钩子
  public mounted() {
    // console.log(this.id);
    // this.getList();
    // console.log(this.tableData,);
    this.getAuth();
  }
  public created() {
    // this.getList();
  }

  public filterNode(value: string, data: SysGrantMenuTreeInfo) {//利用elelmemt方法获取父级的id, 
      if ( !value ) {
         return true;
      }
      if (data.id === value) {
          this.menuIds.push(data.pid);
          this.$refs.tree.filter(data.pid); //迭代
      }
      return true;
  }
  // 方法
  // 获取初始列表
  public async getAuth() {
      const res = await RoleService.getGrantMenuTree(this.id);
      const data: SysGrantMenuTreeInfo[] = res as SysGrantMenuTreeInfo[];
      // 给第三级添加textId字段，用来排序，统一界面显示顺序
      this.serializeAuthMenu(data);
  }
 
   //给第三级添加textId字段，用来排序，统一界面显示顺序
  public serializeAuthMenu(data: SysGrantMenuTreeInfo[]) {
      data.map((item: SysGrantMenuTreeInfo) => {
          if (item.children && item.children.length !== 0) {
              item.children.map(( list: SysGrantMenuTreeInfo) => {
                    if (list.children && list.children.length !== 0) {
                        list.children.map((sub: SysGrantMenuTreeInfo) => {
                              switch (sub.text) {
                                  //添加一个数字
                                  case '查看': sub.textId = 0; break;
                                  case '添加': sub.textId = 1; break;
                                  case '编辑': sub.textId = 2; break;
                                  case '删除': sub.textId = 3; break;
                                  case '质检': sub.textId = 4; break;
                                  case '发布': sub.textId = 5; break;
                                  case '取消发布': sub.textId = 6; break; 
                                  case '权限分配': sub.textId = 7; break;
                                  case '领取': sub.textId = 8; break;
                                  case '转发': sub.textId = 9; break;
                                  case '操作历史': sub.textId = 10; break;
                                  default: sub.textId = 11; break;
                              }
                        });
                        list.children.sort((a, b) => {
                            return a.textId - b.textId;
                        });
                    }

              });
          }
      });
      // 给一二级添加checkedAll字段
      this.addCheckedAllToAuthMenu(data);
  }
  // 给一二级添加checkedAll字段
  public addCheckedAllToAuthMenu(data: SysGrantMenuTreeInfo[]) {
      // 添加字段
      const roleArr: any = [];
      data.map((item: SysGrantMenuTreeInfo, index: number) => { // item 系统==> 大模块
        if (index === 1) {//设置我的主页 选中且 禁止修改
          item.disabled = true;
          item.checkedAll = true;
          item.checked = true;
          item.isIndeterminate = true;
        } else {
          for (const list of item.children) { // list 为小模块 用户、角色、cvs
            list.checkedList = []; // 已选中的子集id
            list.checkedAll = false; // 页面显示 父级 是否全选
            list.isIndeterminate = false;
          }
          item.checkedList = [];
          item.checkedAll = false;
          item.isIndeterminate = false;
        }
        roleArr.push(item);
      });
      this.dataFormat(roleArr);
  }
  // 给添加的字段赋值 checkedList / checkedAll
  public dataFormat(data: SysGrantMenuTreeInfo[]) {
      data.map((item: SysGrantMenuTreeInfo, index: number) => {
          // checked是指该模块有功能被选中，并非全选
          // 针对子集为null的
          if (item.checked && item.children === null) {
              item.checkedAll = true;
          }
          // 针对子集不为null的
          if ( item.children !== null) {
              item.children.map((sub) => {
                  if (sub.checkedAll) {
                      item.checkedList.push(sub.text);
                      //判断显示页面父级是否全选
                      item.checkedAll = (item.checkedList.length === item.children.length ? true : false);
                  }
                  if ( sub.children !== null) {
                    sub.children.map((sub2) => {
                        if (sub2.checked) {
                            this.menuIds.push(sub.id); // 把从服务器获取的数据中选中项的id 放入menuIds
                            // console.log( this.menuIds,"获取到的 this.menuIds");
                            sub.checkedList.push(sub2.text);
                            sub.checkedAll = (sub.checkedList.length ===  sub.children.length ? true : false);
                        }
                    });
                  }
              });
          }
      });
      this.tableData = [...data ];
      this.findCheckedAllId(data);
  }
  // 找出父级的checkAll为true，三级的checked为true的id
  public findCheckedAllId(data: SysGrantMenuTreeInfo[]) {
      //需要遍历出checkedAll为true的项id
      const arr: string[] = [];
      data.map((item: SysGrantMenuTreeInfo) => {
          if ( item.checkedAll) { //一级全选
              arr.push( item.id ); //根据elememt ui组件的父级选中 子集就选中的特性，不用再遍历  
          } else {//一级不全选
              if (item.children !== null) {
                  item.children.map((list) => {
                      if ( list.checkedAll) { //二级全选
                          arr.push( list.id );
                      } else {
                          if (list.children !== null) {
                              list.children.map((list2) => {
                                  if ( list2.checked) { //二级全选
                                      arr.push(list2.id);
                                  }
                              });
                          }
                      }
                  });
              }
          }
      });
      // console.log(arr, "根据arr的数组项里的id值，判断页面是否选中")
      this.$refs.tree.setCheckedKeys(arr); // 根据arr的数组项里的id值，判断页面是否选中
  }
   //角色授权 ===>提交
  public async getRoleAuthList() {
      this.menuIds = this.$refs.tree.getCheckedKeys(); // 只能获取 子集选中的id
     // let arr = []
      this.menuIds.map((item: string) => {
         this.$refs.tree.filter(item); // 触发filterNode 的方法，筛选对应id 的父级id
      });
      //console.log(this.menuIds,"发送的menuIds")
      this.menuIds.map((item: string, index: number) => {
        if (item === '0') { // 删除多余id => 0
          this.menuIds.splice(index, 1);
        }
      });
       //去重
      const idArr = new Set(this.menuIds);
      this.menuIds = Array.from(idArr);
      // 参数
      const query: MenuDto = {
            menuIds: [...this.menuIds],	 // 菜单id列表	array<string>
            roleId: this.id,	// 角色id	string
      };
      const data = await RoleService.grant(query);
      if (data.resCode === '0') {
            this.$message({
              message: '角色授权成功！',
              type: 'success',
              center: true
          });
          this.isShowAuthFun(); // 关闭dialog
      }
  }
  // // 提交
  // public addRole() {
  //    this.isShowAuthFun();
  // }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.sumit{
        margin-top:50px;
    }
</style>
